package logic

import (
	"context"
	"errors"
	"home/model/cache"
	"home/model/mysql"

	"home/homerpc/homerpc"
	"home/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CodeLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCodeLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CodeLoginLogic {
	return &CodeLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 手机号验证码登录
func (l *CodeLoginLogic) CodeLogin(in *homerpc.CodeLoginRequest) (*homerpc.CodeLoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("tel = ?", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("当前用户不存在，请更换")
	}
	result, _ := cache.Rdb.Get(l.ctx, "SendSms_"+in.Tel).Result()
	if result != in.SendCode {
		return nil, errors.New("短信验证码错误，请重新输入")
	}

	return &homerpc.CodeLoginResponse{
		Uid: int64(user.ID),
	}, nil
}
